#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <strings.h>
#include <errno.h> // 全局变量（临界资源），所有库函数都会修改它
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <sys/wait.h>
#include <pthread.h> // POSIX thread

pthread_t t1, t2, t3;

void f(int sig)
{
    printf("%zu收到SIGHUP\n", pthread_self());
}

void *routine1(void *arg)
{
    signal(SIGHUP, f);
    printf("我是: %zu[1]\n", pthread_self());

    sigset_t sig;
    sigemptyset(&sig);
    sigaddset(&sig, SIGINT);
    sigprocmask(SIG_BLOCK, &sig, NULL);

    int i;
    while(1)
        i = i--;
}

void *routine2(void *arg)
{
    printf("我是: %zu[2]\n", pthread_self());
    int i = 0;
    while(i<10)
        i = i++;
}

void *routine3(void *arg)
{
    printf("我是: %zu[3]\n", pthread_self());
    sigset_t sig;
    sigemptyset(&sig);
    sigaddset(&sig, SIGINT);
    sigprocmask(SIG_BLOCK, &sig, NULL);
    int i;
    while(1)
        i = i++;
}

void handler(int sig)
{
    printf("TID: %zu\n", pthread_self());
    pthread_kill(t1, SIGHUP);
}

int main(int argc, char const *argv[])
{
    // 信号响应函数是进程级的，所有线程可见
    signal(SIGINT, handler);

    // PID是系统级的，TID是进程级
    pthread_create(&t1, NULL, routine1, NULL);
    pthread_create(&t2, NULL, routine2, NULL);
    pthread_create(&t3, NULL, routine3, NULL);

    pthread_exit(NULL);
    // while(1)
    //     pause();
}
